const app = getApp()
const request = require('../../utils/request')
const payment = require('../../utils/payment')
const dateUtil = require('../../utils/date')

Page({
  data: {
    // 订单数据
    orders: [],
    // 订单统计
    stats: {
      pending: 0,
      processing: 0,
      delivering: 0,
      completed: 0,
      cancelled: 0,
      refunded: 0
    },
    // 当前状态标签
    currentTab: 'all',
    // 状态类型定义
    tabs: [
      { id: 'all', name: '全部' },
      { id: 'pending', name: '待付款' },
      { id: 'paid', name: '已付款' },
      { id: 'processing', name: '处理中' },
      { id: 'delivering', name: '配送中' },
      { id: 'completed', name: '已完成' },
      { id: 'cancelled', name: '已取消' }
    ],
    // 状态映射
    statusMap: {
      PENDING_PAYMENT: { text: '待付款', color: '#ff9800', actionText: '去支付' },
      PAID: { text: '已付款', color: '#2196f3', actionText: '催单' },
      PROCESSING: { text: '处理中', color: '#2196f3', actionText: '联系商家' },
      DELIVERING: { text: '配送中', color: '#00bcd4', actionText: '查看配送' },
      COMPLETED: { text: '已完成', color: '#4caf50', actionText: '评价' },
      CANCELLED: { text: '已取消', color: '#9e9e9e', actionText: '删除' },
      REFUNDED: { text: '已退款', color: '#9e9e9e', actionText: '删除' }
    },
    // 页面加载状态
    loading: false,
    // 是否还有更多数据
    hasMore: true,
    // 当前页码
    page: 0,
    // 页大小
    pageSize: 10,
    // 用户ID
    userId: null,
    // 是否显示空状态
    isEmpty: false,
    // 是否初次加载
    isFirstLoad: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({
      userId: app.getSafeUserId(),
      loading: true
    })
    
    // 获取订单统计数据
    this.fetchOrderStats()
    
    // 获取订单列表
    this.fetchOrders(true)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 0,
      hasMore: true
    })
    
    // 重新获取订单列表
    this.fetchOrders(true)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      
      this.fetchOrders(false)
    }
  },

  /**
   * 获取订单统计
   */
  fetchOrderStats() {
    const userId = this.data.userId
    
    request.get(`/orders/stats/user/${userId}`, {}, {
      mock: {
        pendingPayment: 1,
        processing: 2,
        delivering: 1,
        completed: 5,
        cancelled: 1,
        totalOrders: 10,
        totalAmount: 520.88
      }
    }).then(res => {
      if (res.code === 200 && res.data) {
        this.setData({
          stats: {
            pending: res.data.pendingPayment || 0,
            processing: res.data.processing || 0,
            delivering: res.data.delivering || 0,
            completed: res.data.completed || 0,
            cancelled: res.data.cancelled || 0,
            refunded: res.data.refunded || 0
          }
        })
      }
    }).catch(err => {
      console.error('获取订单统计失败:', err)
    })
  },

  /**
   * 获取订单列表
   */
  fetchOrders(isRefresh) {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const { userId, page, pageSize, currentTab } = this.data
    
    // 构建查询参数
    const params = { page, size: pageSize }
    
    // 根据当前标签筛选状态
    if (currentTab !== 'all') {
      params.status = this.getStatusByTab(currentTab)
    }
    
    // 请求API
    request.get(`/orders/user/${userId}`, params, {
      // 模拟数据
      mock: this.getMockOrders(page, currentTab)
    }).then(res => {
      if (res.code === 200 && res.data) {
        const { content, totalElements, totalPages, last } = res.data
        
        // 处理订单数据
        const formattedOrders = this.formatOrders(content)
        
        // 更新列表
        this.setData({
          orders: isRefresh ? formattedOrders : [...this.data.orders, ...formattedOrders],
          hasMore: !last,
          loading: false,
          isEmpty: (isRefresh && formattedOrders.length === 0),
          isFirstLoad: false
        })
      } else {
        this.setData({
          loading: false,
          isFirstLoad: false
        })
      }
      
      // 停止下拉刷新动画
      wx.stopPullDownRefresh()
    }).catch(err => {
      console.error('获取订单列表失败:', err)
      this.setData({
        loading: false,
        isFirstLoad: false
      })
      
      // 停止下拉刷新动画
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 格式化订单数据
   */
  formatOrders(orders) {
    return orders.map(order => {
      // 获取状态信息
      const statusInfo = this.data.statusMap[order.status] || {
        text: '未知状态',
        color: '#9e9e9e',
        actionText: '查看详情'
      }
      
      // 格式化时间
      const createdAt = order.createdAt ? dateUtil.formatDateTime(new Date(order.createdAt)) : ''
      
      return {
        ...order,
        statusText: statusInfo.text,
        statusColor: statusInfo.color,
        actionText: statusInfo.actionText,
        formattedTime: createdAt,
        // 订单总价格格式化
        formattedTotalAmount: order.totalAmount.toFixed(2)
      }
    })
  },

  /**
   * 根据标签获取状态值
   */
  getStatusByTab(tab) {
    const statusMap = {
      'pending': 'PENDING_PAYMENT',
      'paid': 'PAID',
      'processing': 'PROCESSING',
      'delivering': 'DELIVERING',
      'completed': 'COMPLETED',
      'cancelled': 'CANCELLED'
    }
    
    return statusMap[tab] || null
  },

  /**
   * 切换订单状态标签
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    
    this.setData({
      currentTab: tab,
      page: 0,
      hasMore: true,
      orders: []
    })
    
    // 重新加载订单
    this.fetchOrders(true)
  },

  /**
   * 查看订单详情
   */
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id
    
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${orderId}`
    })
  },

  /**
   * 订单操作按钮
   */
  handleOrderAction(e) {
    const { id, status } = e.currentTarget.dataset
    
    // 根据订单状态执行不同操作
    if (status === 'PENDING_PAYMENT') {
      // 去支付
      this.payOrder(id)
    } else if (status === 'PAID' || status === 'PROCESSING') {
      // 催单
      this.remindOrder(id)
    } else if (status === 'DELIVERING') {
      // 查看配送
      this.viewDelivery(id)
    } else if (status === 'COMPLETED') {
      // 评价订单
      this.rateOrder(id)
    } else if (status === 'CANCELLED' || status === 'REFUNDED') {
      // 删除订单
      this.deleteOrder(id)
    } else {
      this.viewOrderDetail(e)
    }
  },

  /**
   * 支付订单
   */
  payOrder(orderId) {
    // 获取订单信息
    request.get(`/orders/${orderId}`, {}, {
      mock: {
        id: orderId,
        orderNo: 'ORD' + Date.now(),
        status: 'PENDING_PAYMENT',
        totalAmount: 88.8
      }
    }).then(res => {
      if (res.code === 200 && res.data) {
        const order = res.data
        
        // 调用支付
        payment.payOrder(orderId, order.totalAmount, 'WECHAT_PAY')
          .then(result => {
            if (result.success) {
              // 支付成功，刷新订单列表
              this.setData({
                page: 0,
                hasMore: true
              })
              this.fetchOrders(true)
              this.fetchOrderStats()
            } else {
              wx.showToast({
                title: result.message || '支付失败',
                icon: 'none'
              })
            }
          })
          .catch(err => {
            console.error('支付失败:', err)
            wx.showToast({
              title: '支付过程出现错误',
              icon: 'none'
            })
          })
      }
    }).catch(err => {
      console.error('获取订单信息失败:', err)
      wx.showToast({
        title: '获取订单信息失败',
        icon: 'none'
      })
    })
  },

  /**
   * 催单
   */
  remindOrder(orderId) {
    wx.showToast({
      title: '已通知商家加速处理',
      icon: 'success'
    })
  },

  /**
   * 查看配送
   */
  viewDelivery(orderId) {
    wx.navigateTo({
      url: `/pages/delivery/delivery?id=${orderId}`
    })
  },

  /**
   * 评价订单
   */
  rateOrder(orderId) {
    wx.navigateTo({
      url: `/pages/rate/rate?id=${orderId}`
    })
  },

  /**
   * 删除订单
   */
  deleteOrder(orderId) {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个订单吗？删除后将不再显示',
      success: (res) => {
        if (res.confirm) {
          // 从订单列表中移除
          const orders = this.data.orders.filter(order => order.id !== orderId)
          this.setData({ orders })
          
          // 提示成功
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },

  /**
   * 申请退款
   */
  requestRefund(e) {
    const orderId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '申请退款',
      content: '确定要申请退款吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/refund/refund?id=${orderId}`
          })
        }
      }
    })
  },

  /**
   * 返回首页
   */
  goToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  /**
   * 模拟订单数据
   */
  getMockOrders(page, tab) {
    // 基础模拟数据
    const baseOrders = [
      {
        id: 1001,
        orderNo: 'ORD20230601001',
        status: 'PENDING_PAYMENT',
        totalAmount: 55.50,
        productAmount: 48.50,
        deliveryFee: 7.00,
        discountAmount: 0.00,
        createdAt: '2023-08-15T14:30:00',
        storeName: '美味餐厅',
        orderItems: [
          { productId: 101, name: '黄焖鸡米饭', price: 22.00, quantity: 1 },
          { productId: 102, name: '可乐', price: 6.50, quantity: 1 },
          { productId: 103, name: '炸鸡腿', price: 10.00, quantity: 2 }
        ]
      },
      {
        id: 1002,
        orderNo: 'ORD20230602001',
        status: 'PAID',
        totalAmount: 36.00,
        productAmount: 31.00,
        deliveryFee: 5.00,
        discountAmount: 0.00,
        createdAt: '2023-08-14T12:20:00',
        storeName: '汉堡王',
        orderItems: [
          { productId: 201, name: '皇堡', price: 21.00, quantity: 1 },
          { productId: 202, name: '薯条', price: 10.00, quantity: 1 }
        ]
      },
      {
        id: 1003,
        orderNo: 'ORD20230603001',
        status: 'PROCESSING',
        totalAmount: 89.00,
        productAmount: 84.00,
        deliveryFee: 5.00,
        discountAmount: 0.00,
        createdAt: '2023-08-14T18:10:00',
        storeName: '必胜客',
        orderItems: [
          { productId: 301, name: '超级至尊披萨', price: 69.00, quantity: 1 },
          { productId: 302, name: '意面', price: 15.00, quantity: 1 }
        ]
      },
      {
        id: 1004,
        orderNo: 'ORD20230604001',
        status: 'DELIVERING',
        totalAmount: 45.00,
        productAmount: 40.00,
        deliveryFee: 5.00,
        discountAmount: 0.00,
        createdAt: '2023-08-13T11:30:00',
        storeName: '沙县小吃',
        orderItems: [
          { productId: 401, name: '拌面', price: 15.00, quantity: 1 },
          { productId: 402, name: '蒸饺', price: 12.00, quantity: 1 },
          { productId: 403, name: '鸡汤', price: 13.00, quantity: 1 }
        ]
      },
      {
        id: 1005,
        orderNo: 'ORD20230605001',
        status: 'COMPLETED',
        totalAmount: 68.00,
        productAmount: 63.00,
        deliveryFee: 5.00,
        discountAmount: 0.00,
        createdAt: '2023-08-12T19:40:00',
        storeName: '川湘菜馆',
        orderItems: [
          { productId: 501, name: '水煮鱼', price: 38.00, quantity: 1 },
          { productId: 502, name: '青椒土豆丝', price: 15.00, quantity: 1 },
          { productId: 503, name: '米饭', price: 5.00, quantity: 2 }
        ]
      },
      {
        id: 1006,
        orderNo: 'ORD20230606001',
        status: 'CANCELLED',
        totalAmount: 33.00,
        productAmount: 28.00,
        deliveryFee: 5.00,
        discountAmount: 0.00,
        createdAt: '2023-08-10T20:15:00',
        storeName: '粤式茶餐厅',
        orderItems: [
          { productId: 601, name: '叉烧包', price: 15.00, quantity: 1 },
          { productId: 602, name: '肠粉', price: 13.00, quantity: 1 }
        ]
      }
    ]

    // 根据标签筛选
    let filteredOrders = baseOrders
    if (tab !== 'all') {
      const statusMap = this.getStatusByTab(tab)
      filteredOrders = baseOrders.filter(order => order.status === statusMap)
    }
    
    // 模拟分页
    const pageSize = this.data.pageSize
    const startIndex = page * pageSize
    const endIndex = startIndex + pageSize
    const pagedOrders = filteredOrders.slice(startIndex, endIndex)
    
    // 构建分页响应
    return {
      content: pagedOrders,
      pageable: {
        pageNumber: page,
        pageSize: pageSize
      },
      totalPages: Math.ceil(filteredOrders.length / pageSize),
      totalElements: filteredOrders.length,
      last: endIndex >= filteredOrders.length,
      first: page === 0,
      size: pageSize,
      number: page
    }
  }
}) 